package com.zzy.customglide.load;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;

import com.zzy.customglide.resource.Value;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class LoadDataManager implements ILoadData, Runnable {
    String path;
    ResponseListener responseListener;
    Context context;

    @Override
    public Value loadResource(String url, ResponseListener responseListener, Context context) {
        this.path = url;
        this.responseListener = responseListener;
        this.context = context;

        //加载网络图片
        Uri uri = Uri.parse(url);
        if ("HTTPS".equalsIgnoreCase(uri.getScheme())) {
            new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()).execute(this);
        }


        return null;
    }

    @Override
    public void run() {
        InputStream inputStream = null;
        HttpURLConnection httpURLConnection = null;
        try {
            URL url = new URL(path);
            URLConnection urlConnection = url.openConnection();
            httpURLConnection= (HttpURLConnection) urlConnection;
            httpURLConnection.setConnectTimeout(5000);
           final int response= httpURLConnection.getResponseCode();
           if(response==HttpURLConnection.HTTP_OK){
               inputStream= httpURLConnection.getInputStream();
              final Bitmap bitmap= BitmapFactory.decodeStream(inputStream);
              new Handler(Looper.getMainLooper()).post(new Runnable() {
                  @Override
                  public void run() {
                      Value value=Value.getInstance();
                      value.setmBitmap(bitmap);
                    responseListener.responseSuccess(value);
                  }
              });

           }else{
               new Handler(Looper.getMainLooper()).post(new Runnable() {
                   @Override
                   public void run() {
                       responseListener.responseException(new Exception( ));
                   }
               });
           }


        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {

                }
            }
            if(httpURLConnection!=null){
                httpURLConnection.disconnect();
            }
        }

    }
}
